package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import com.tutk.p2p.ConnectionEntity;

import org.json.JSONException;
import org.json.JSONObject;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.BoxDetailMoreAdapter;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.manager.PlaceManager;
import cn.innosmart.aq.manager.SystemManager;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.AssignActivity;
import cn.innosmart.aq.view.activity.AssignProviderActivity;
import cn.innosmart.aq.view.activity.BoxDetailActivity;
import cn.innosmart.aq.view.activity.CountSettingActivity;
import cn.innosmart.aq.view.activity.FullscreenMonitoringActivity;
import cn.innosmart.aq.view.activity.ReminderListActivity;
import cn.innosmart.aq.view.activity.WorkLogActivity;
import cn.innosmart.aq.wifiset.WifiListActivity;

/**
 * Created by David on 2015/7/23.
 */
public class BoxDetailMoreFragment extends BaseFragment {
    private View view;
    private ConnectionEntity connectionEntity;
    private GridView gvMore;
    private BoxDetailActivity activity;

    private AquariumBean currentAquariumBean;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    boxDetailMoreAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    };


    /**
     * 更多菜单的点击事件监听
     */
    public AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
                case 0:
                    //跳转到设备管理界面
                    activity.switchManagerFragment();
                    break;
                case 1:
                    //重启Box
                    showReboot();
                    break;
                case 2:
                    //进入Wifi列表
                    Intent wifiListIntent = new Intent(getActivity(), WifiListActivity.class);
                    getActivity().startActivity(wifiListIntent);
                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
                case 3:
                    //enter maintain mode
                    showMaintainConfimDialog();
                    break;

                case 4: {
                    Intent intent = new Intent(getActivity(), AssignProviderActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
                break;

                case 5: {
                    Intent intent = new Intent(getActivity(), AssignActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
                break;

                case 6: {
                    Intent intent = new Intent(getActivity(), FullscreenMonitoringActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
                break;
//                case 3:
//                    if (SystemConstant.loginStatus == SystemConstant.Online) {
//                        //在线状态下，进入日志界面
//                        Intent intents = new Intent(getActivity(), WorkLogActivity.class);
//                        getActivity().startActivity(intents);
//                        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//                    } else {
//                        showToast(getString(R.string.operate_befor_login));
//                    }
//                    break;
//                case 4:
//                    //进入备忘提醒界面
//                    Intent intent = new Intent(getActivity(), ReminderListActivity.class);
//                    startActivity(intent);
//                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//                    break;
            }
        }
    };
    private BoxDetailMoreAdapter boxDetailMoreAdapter;
    /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private AquariumBean aquariumBean;

    public void setConnectionEntity(ConnectionEntity connectionEntity) {
        this.connectionEntity = connectionEntity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        currentAquariumBean = ((BoxDetailActivity) getActivity()).aquariumBean;

        view = inflater.inflate(R.layout.fragment_more, container, false);
        gvMore = (GridView) view.findViewById(R.id.gv_more);
        boxDetailMoreAdapter = new BoxDetailMoreAdapter(getActivity());
        boxDetailMoreAdapter.updateMaintainMode(currentAquariumBean.getMaintainMode());
        gvMore.setAdapter(boxDetailMoreAdapter);
        gvMore.setOnItemClickListener(onItemClickListener);
        activity = (BoxDetailActivity) getActivity();
        setHasOptionsMenu(true);
        setBar();
        return view;
    }

    /**
     * 弹出重启的对话框
     */
    private void showReboot() {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(getActivity());
        customsizeDialog.setTitle(R.string.dialog_title_alert);
        customsizeDialog.setCancelable(false);
        customsizeDialog.setContent(getString(R.string.reboot_sure));
        customsizeDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customsizeDialog.dismiss();
                JSONObject jsonParams = new JSONObject();
                try {
                    jsonParams.put("cmdline", "reboot");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                activity.loadingDialog();
                //发出重启指令
                SystemManager.getInstance().ExecuteShellScript(connectionEntity, jsonParams.toString(), new SystemManager.onReboot() {
                    @Override
                    public void onRebootCallBack(int ret) {
                        activity.hideloadingDialog();
                        if (ret == 0) {
//                            activity.exit();
                        } else if (ret == -1) {
                            showToast(getString(R.string.dialog_action_error));
                        }
                    }
                });
            }
        });
        customsizeDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }

    /**
     * 弹出重启的对话框
     */
    private void showMaintainConfimDialog() {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(getActivity());

        customsizeDialog.setTitle(R.string.dialog_title_alert);
        customsizeDialog.setCancelable(false);

        if (currentAquariumBean.getMaintainMode() == 0) {
            customsizeDialog.setContent(getString(R.string.enable_maintain_mode_long), Gravity.LEFT);
        } else {
            customsizeDialog.setContent(getString(R.string.disable_maintain_mode_long), Gravity.CENTER);
        }

        customsizeDialog.setPositiveButton((currentAquariumBean.getMaintainMode() == 0) ? R.string.enable_maintain_mode : R.string.disable_maintain_mode, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customsizeDialog.dismiss();
                JSONObject jsonParams = new JSONObject();
                try {
                    jsonParams.put("id", ((BoxDetailActivity) getActivity()).aquariumBean.getId());
                    int maintain = 0;
                    if (currentAquariumBean.getMaintainMode() == 0) {
                        maintain = 1;
                    } else {
                        maintain = 0;
                    }
                    jsonParams.put("maintain", maintain);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                activity.loadingDialog();

                //发出enable maintain
                PlaceManager.getInstance().ChangeMaintainMode(connectionEntity, jsonParams.toString(), new PlaceManager.ChangeMaintainModeCallback() {
                    @Override
                    public void onChangeMaintainModeCallback(int ret) {
                        System.out.println("onChangeMaintainModeCallback, ret:" + ret);
                        activity.hideloadingDialog();

                        if (ret == 0) {//success
                            if (currentAquariumBean.getMaintainMode() == 0) {
                                currentAquariumBean.setMaintainMode(1);
                            } else {
                                currentAquariumBean.setMaintainMode(0);
                            }
                            boxDetailMoreAdapter.updateMaintainMode(currentAquariumBean.getMaintainMode());
                            mHandler.sendEmptyMessage(1);//refresh gridview
                        }

                    }
                });
            }
        });
        customsizeDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }

    /**
     * 设置Toolbar菜单
     */
    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);

    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    /**
     * 设置当前鱼缸
     *
     * @param aquarium
     */
    public void setAquarium(AquariumBean aquarium) {
        this.aquariumBean = aquarium;
    }

    @Override
    public void onResume() {
        getActivity().invalidateOptionsMenu();
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

}
